import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const SearchResult = () => import('@/views/search/result')
const Article = () => import('@/views/article')
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Profile = () => import('@/views/user/profile')
const Chat = () => import('@/views/user/chat')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/search', component: Search },
    { path: '/userProfile', component: Profile },
    { path: '/chat', component: Chat },
    { path: '/searchresult', component: SearchResult, name: 'SearchResult' },
    { path: '/article/:article_id', component: Article, name: 'Article' },
    {
      path: '/',
      component: Layout,
      children: [
        { path: 'home', component: Home, meta: { isKeepAlive: true } },
        { path: 'question', component: Question },
        { path: 'video', component: Video },
        { path: 'user', component: User }
      ],
      redirect: '/home'
    }
  ]
})

const AuthUrls = ['/user', '/pay']
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  if (AuthUrls.includes(to.path)) {
    if (token) {
      next()
    } else {
      router.push({
        path: '/login',
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})

export default router
